package com.android.love.ui;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.love.R;
import com.android.love.adapter.BannerAdapter;
import com.android.love.adapter.CommentAdapter_1;
import com.android.love.net.AutoTask;
import com.android.love.net.UriHelper;
import com.android.love.util.ActivityUtil;
import com.android.love.util.FileUtil;
import com.android.love.util.ImageUtils;
import com.android.love.util.LogUtil;
import com.android.love.view.CirclePageIndicator;
import com.android.love.view.CustomViewPager;
import com.android.love.view.GridViewWithHeaderBaseAdapter.GridItemClickListener;
import com.android.love.vo.Goods;
import com.android.love.vo.MyRequest;
import com.android.love.vo.TopGoods;
import com.github.kevinsawicki.wishlist.ViewFinder;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.igexin.slavesdk.MessageManager;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class HomeActivity extends BasePageActivity implements GridItemClickListener {

    private ViewFinder homeFider;

    private SparseArray<List> comments;

    /** 顶部滚动商品列表 **/
    private List<TopGoods> topGoods;

    /** 推荐商品列表 **/
    private List<Goods> goods;

    // private MyPosterView postView;

    // private PullToRefreshPLAListView mPullToRefreshGridView;
    private PullToRefreshListView mPullToRefreshGridView;

    // private MultiColumnListView mGridView;
    private ListView mGridView;

    // private CommentAdapter mCommentAdapter;
    private CommentAdapter_1 mCommentAdapter;

    /** 页数 **/
    private int page=1;

    /** 是否弹出加载中提示 **/
    private boolean show=true;

    private View postHeaderView;

    private View footView;

    private Animation mRotaAnimation;

    private ImageView iv_shuaxin;

    private boolean refresh;

    private AutoTask mAutoTask;

    private CustomViewPager mPager;

    private CirclePageIndicator mIndicator;

    // 要展示的界面
    private List<View> views=null;

    /** 轮转大图图片集合 **/
    private List<String> topImages=Collections.emptyList();;

    private BannerAdapter mAdapter;

    private Handler handler=new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch(msg.what) {
                case VIEWPAGER:
                    if(mPager.getCurrentItem() < mPager.getAdapter().getCount() - 1)
                        mPager.setCurrentItem(mPager.getCurrentItem() + 1);
                    else
                        mPager.setCurrentItem(0);
                    break;

                default:
                    break;
            }
        };
    };

    private ProgressBar pb_loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View homeView=inflater.inflate(R.layout.activity_recomment, null);
        setContentView(homeView);
        // if (savedInstanceState != null) {
        // LogUtil.i(TAG, "savedInstanceState  not null");
        // page = savedInstanceState.getInt(PAGE);
        // List<Goods> sGoods = (List<Goods>) savedInstanceState
        // .getSerializable(COMMENTS);
        // List<TopGoods> sTopGoods = (List<TopGoods>) savedInstanceState
        // .getSerializable(TOPCOMMENTS);
        // if (goods != null)
        // sGoods.clear();
        // else
        // sGoods = new ArrayList<Goods>();
        // updateGoods(sGoods);
        // if (topGoods != null)
        // topGoods.clear();
        // else
        // topGoods = new ArrayList<TopGoods>();
        // topGoods.addAll(sTopGoods);
        // updateTop();
        // } else {
        LogUtil.i(TAG, "savedInstanceState   null");
        homeFider=new ViewFinder(homeView);
        process();
        setListener();
        getData();
        // }
        LogUtil.i(TAG, "onCreate");
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtil.i(TAG, "onNewIntent");
    }

    @Override
    protected void onResume() {
        mApplication.setDefaultIndex(HOME);
        super.onResume();
        LogUtil.i(TAG, "onResume");
    }

    @Override
    public void handle(int tag, Object object) {
        super.handle(tag, object);
        switch(tag) {
            case LOAD_HOME:
                if(footView != null)
                    footView.setVisibility(View.GONE);
                if(object != null) {
                    LogUtil.i(TAG, "success");
                    comments=(SparseArray<List>)object;
                    List<Goods> recommends=comments.get(0);
                    if(comments.get(1) != null && comments.get(1).size() > 0 && page == 1 && !refresh) {
                        topGoods=comments.get(1);
                        topImages=new ArrayList<String>();
                        for(TopGoods topGood: topGoods) {
                            // FileUtil.saveTempFile(topGood, context);
                            topImages.add(topGood.getTopic_image());
                        }
                        updateTop();
                    }
                    if(recommends != null && recommends.size() > 0) {
                        updateGoods(recommends);
                        // for(Goods goods: recommends) {
                        // FileUtil.saveTempFile(goods, context);
                        // }
                    } else {
                        ActivityUtil.show(HomeActivity.this, "没有更多数据");
                    }
                    if(refresh) {
                        // mCommentAdapter.notifyDataSetChanged();
                        ActivityUtil.show(HomeActivity.this, "刷新成功");
                        refresh=false;
                        stopRinghtBtn();
                        // if(!postView.isRun()) {
                        // postView.setRun(true);
                        // }

                    }
                } else {
                	page--;
                }
                // mAutoTask.execute(new Void[0]);
                mPullToRefreshGridView.onRefreshComplete();
                break;

            default:
                break;
        }

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        LogUtil.i(TAG, "onPause---");
        super.onPause();
        // if (mAutoTask != null)
        // mAutoTask.stop();
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        // if (mAutoTask != null)
        // mAutoTask.stop();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if(mAutoTask != null) {
            mAutoTask.stop();
        }
    }

    /**
     * @param tops
     */
    private void updateTop() {
        // // postView.setData(images, this, true, 5, false, 0, refresh);
        if(topImages == null || topImages.size() == 0)
            return;
        // views.clear();
        for(int i=0; i < topImages.size(); i++) {
            final int position=i;
            ImageView img=new ImageView(context);
            LinearLayout ll=new LinearLayout(context);
            ll.addView(img);
            loader.displayImageForSize(topImages.get(i), img, ImageUtils.getOptions(R.drawable.zw1),
                new SimpleImageLoadingListener(), 0, 0, 0, 0, ActivityUtil.getScreenSize()[0], ActivityUtil.dip2px(context, 150),
                1f, true);
            // loader.displayImage(topImages.get(i), img);
            ll.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Intent intent=new Intent(context, DetailActivity.class);
                    // if (position - 1 >= 0)
                    // intent.putExtra("goods", topGoods.get(position - 1));
                    // else
                    intent.putExtra("type", 2);
                    intent.putExtra("position", position);
                    intent.putExtra("goods", (Serializable)topGoods);
                    startActivity(intent);
                }
            });
            views.add(ll);

        }
        mAdapter.notifyDataSetChanged();
        mIndicator.notifyDataSetChanged();
        mAutoTask=new AutoTask(mPager, handler);
        //
        // mAutoTask = new AutoTask(mPager);
        // mAutoTask.execute(new Void[0]);
    }

    private void updateGoods(List<Goods> recommends) {
        goods.addAll(recommends);
        if(mCommentAdapter == null) {
            mCommentAdapter=new CommentAdapter_1(context, loader, goods, 0);
            mCommentAdapter.setNumColumns(2);
            mCommentAdapter.setOnGridClickListener(this);
            mGridView.setAdapter(mCommentAdapter);
        } else {
            mCommentAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void process() {
        super.process();
        goods=new ArrayList<Goods>();
        views=new ArrayList<View>();
        mPullToRefreshGridView=(PullToRefreshListView)findViewById(R.id.pull_refresh_grid);
        mGridView=mPullToRefreshGridView.getRefreshableView();
        iv_shuaxin=homeFider.imageView(R.id.iv_shuaxin);
        pb_loading=homeFider.find(R.id.pb_loading);
        postHeaderView=inflater.inflate(R.layout.home_poster, null);
        // postView=(MyPosterView)postHeaderView.findViewById(R.id.home_Poster);
        mGridView.addHeaderView(postHeaderView);
        footView=LayoutInflater.from(context).inflate(R.layout.loading_item, null);
        TextView textView=(TextView)footView.findViewById(R.id.tv_loading);
        textView.setText("正在加载.....");
        mGridView.addFooterView(footView);
        footView.setVisibility(View.GONE);
        // mGridView.setColumnNumber(1);
        setTopPager();
    }

    /**
     * 设置顶部轮转大图
     */
    private void setTopPager() {
        mAdapter=new BannerAdapter(this, views);
        mPager=(CustomViewPager)postHeaderView.findViewById(R.id.pager);
        mPager.setAdapter(mAdapter);
        mIndicator=(CirclePageIndicator)postHeaderView.findViewById(R.id.indicator);
        mIndicator.setViewPager(mPager);
        final float density=getResources().getDisplayMetrics().density;
        mIndicator.setBackgroundColor(0x99000000);
        mIndicator.setRadius(4 * density);
        mIndicator.setFillColor(0xFFE2017B);
        mIndicator.setPageColor(0xEECCCCCC);
        mIndicator.setStrokeColor(0xFF000000);
        mIndicator.setStrokeWidth(0 * density);
    }

    @Override
    protected void getData() {
        // if (mAutoTask != null)
        // mAutoTask.stop();
        super.getData();
        MyRequest req=new MyRequest();
        req.authority=UriHelper.REALM_NAME;
        req.path=UriHelper.URL_RECOMMENT;
        req.paramers=generateParams(page);
        // if (show) {
        // show(pb_loading);
        // } else
        // hide(pb_loading);
        getDataFromTask(context, LOAD_HOME, req, comments, show, true);
    }

    @Override
    protected void setListener() {
        super.setListener();
        iv_shuaxin.setOnClickListener(this);
        mPullToRefreshGridView.getLoadingLayoutProxy();
        mPullToRefreshGridView.setMode(Mode.DISABLED);
        mPullToRefreshGridView.setScrollbarFadingEnabled(true);
        mPullToRefreshGridView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

            @Override
            public void onLastItemVisible() {
                LogUtil.i(TAG, "OnLastItemVisibleListener....");
                if(footView != null)
                    footView.setVisibility(View.VISIBLE);
                show=false;
                page++;
                getData();
            }
        });

        // mGridView.setOnItemClickListener(new OnItemClickListener() {
        //
        // @Override
        // public void onItemClick(PLA_AdapterView<?> parent, View view,
        // int position, long id) {
        // LogUtil.i(TAG, "position...." + position);
        // Intent intent = new Intent(context, DetailActivity.class);
        // if (position - 1 >= 0)
        // intent.putExtra("goods", goods.get(position - 1));
        // else
        // intent.putExtra("goods", goods.get(position));
        // startActivity(intent);
        //
        // }
        // });
    }

    /**
     * 得到传递的参数
     * 
     * @return
     * @throws JSONException
     * @throws IOException
     */
    public Map<String, String> generateParams(int page) {
        JSONObject json=new JSONObject();
        TreeMap<String, String> params=new TreeMap<String, String>();
        params.put("app_key", "android");
        params.put("v", "1.0");
        params.put("page", page + "");
        params.put("count", "10");
        return params;
    }

    // @Override
    // public void onMyclick(int position) {
    // // TODO Auto-generated method stub
    // LogUtil.e(TAG, "onMyclick---" + position);
    // Intent intent=new Intent(context, DetailActivity.class);
    // // if (position - 1 >= 0)
    // // intent.putExtra("goods", topGoods.get(position - 1));
    // // else
    // intent.putExtra("goods", topGoods.get(position));
    // startActivity(intent);
    // }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch(v.getId()) {
            case R.id.iv_shuaxin:
                refresh=true;
                // postView.stopTask();
                // if(postView.isRun()) {
                // postView.setRun(false);
                // }
                // postView.clearMemory();
                // mAutoTask.stop();
                show=false;
                goods.clear();
                topGoods.clear();
                page=1;
                onRightBtnRota();
                getData();
                break;

            default:
                break;
        }
    }

    protected void onRightBtnRota() {
        if(mRotaAnimation == null) {
            mRotaAnimation=AnimationUtils.loadAnimation(this, R.anim.rota360);
        }
        mRotaAnimation.setRepeatCount(100000);
        mRotaAnimation.setRepeatMode(Animation.RESTART);
        iv_shuaxin.clearAnimation();
        iv_shuaxin.startAnimation(mRotaAnimation);
    }

    protected void stopRinghtBtn() {
        iv_shuaxin.clearAnimation();
    }

    @Override
    public void onGridItemClicked(View v, int position, long itemId) {
        Intent intent=new Intent(context, DetailActivity.class);
        // if (position - 1 >= 0)
        // intent.putExtra("goods", goods.get(position - 1));
        // else
        // intent.putExtra("goods", goods.get(position));
        intent.putExtra("type", 1);
        intent.putExtra("goods", (Serializable)goods);
        intent.putExtra("position", position);
        // intent.putExtra("topgoods", (Serializable)goods);
        startActivity(intent);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        LogUtil.i(TAG, "onSaveInstanceState---");
        outState.putSerializable(COMMENTS, (Serializable)goods);
        outState.putSerializable(TOPCOMMENTS, (Serializable)goods);
        outState.putInt(PAGE, page);
        super.onSaveInstanceState(outState);
    }

    // @Override
    // protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // // super.onRestoreInstanceState(savedInstanceState);
    // LogUtil.i(TAG, "onRestoreInstanceState---");
    // }

}
